import axios from 'axios'
import router from './router'
import Element from "element-ui";

//8081后端端口
axios.defaults.baseURL = "http://localhost:8081"

const request = axios.create({
    timeout: 5000,
    headers:  {
        'Content-Type': "application/json; charset=utf-8"
    }
})

//1:设置请求拦截器
request.interceptors.request.use(config => {
    //为每一个请求添加token
    config.headers['Authorization'] = localStorage.getItem("token");
    return config;
})
//2:设置响应拦截器
request.interceptors.response.use(
    //中间没有出现异常,正常返回
    response  => {
        let res = response.data
        //拦截:判断code是否为200
        if(res.code ===  200){
            //取消拦截,返回结果
            return response
        }else{
            Element.Message.error(!res.msg? '系统异常':res.msg);
            return Promise.reject(response.data.msg)
        }
    },
    //中间出现一些异常
    error => {

        if(error.response.data){
            error.massage = error.response.data.msg;
        }
        //没有权限则跳转到登陆页面
        if(error.response.status ===  401){
            router.push('/login')
        }
        //弹窗显示系统异常
        Element.Message.error(error.massage,{duration: 3000})
        return Promise.reject(error)
    }
)

export default request